<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddGrades" v-hasPermi="['system:grades:add']">新增年级</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['system:classes:export']">
        <el-upload multiple :action="uploadFileUrl" accept=".xlsx" :on-success="handleImport" :show-file-list="false" :headers="headers">
          <el-button type="warning" plain icon="el-icon-upload" size="mini">导入分班学生</el-button>
        </el-upload>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-table v-loading="gradesLoading" ref="gradeTable" :data="gradesList" highlight-current-row border @current-change="handleCurrentChange">
          <el-table-column label="年级名称" align="center" prop="gradeName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateGrade(scope.row)" v-hasPermi="['system:grades:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteGrade(scope.row)" v-hasPermi="['system:grades:remove']">删除</el-button>
              <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAddClass(scope.row)" v-hasPermi="['system:classes:add']">新增班级</el-button>
              <el-button size="mini" type="text" icon="el-icon-download" @click="handleExport(scope.row)" v-hasPermi="['system:grades:export']">导出学生信息</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="12">
        <el-table v-loading="classesLoading" :data="classesList" border>
          <el-table-column label="班级ID" align="center" prop="cid" />
          <el-table-column label="班级名称" align="center" prop="className" />
          <!-- <el-table-column label="课表ID" align="center" prop="scheduleId" /> -->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateClass(scope.row)" v-hasPermi="['system:classes:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteClass(scope.row)" v-hasPermi="['system:classes:remove']">删除</el-button>
              <el-button size="mini" type="text" icon="el-icon-view" @click="handleViewClass(scope.row)">查看课表</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- 添加或修改年级对话框 -->
    <el-dialog title="年级管理" :visible.sync="gradeOpen" width="500px" append-to-body>
      <el-form ref="gradeForm" :model="gradeForm" :rules="gradeRules" label-width="80px">
        <el-form-item label="年级名称" prop="gradeName">
          <el-input v-model="gradeForm.gradeName" placeholder="请输入年级名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGradeForm">确 定</el-button>
        <el-button @click="cancelGrade">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改班级对话框 -->
    <el-dialog title="班级管理" :visible.sync="classOpen" width="500px" append-to-body>
      <el-form ref="classForm" :model="classForm" :rules="classRules" label-width="80px">
        <el-form-item label="年级" prop="gid">
          <el-select v-model="classForm.gid" placeholder="请选择年级" style="width:100%">
            <el-option v-for="dict in gradesList" :key="dict.gid" :label="dict.gradeName" :value="dict.gid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="classForm.className" placeholder="请输入班级名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitClassForm">确 定</el-button>
        <el-button @click="cancelClass">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="kbTitle" :visible.sync="kbOpen" width="1200px" append-to-body>
      <table>
        <tbody>
          <tr>
            <th>时间</th>
            <th colspan="1" v-for="item in dict.type.sys_week">{{item.label}}</th>
          </tr>
          <tr v-for="rowItem in 12">
            <td v-for="cellItem in dict.type.sys_week.length+1">{{filterLabel(rowItem,cellItem)}}</td>
          </tr>
        </tbody>
      </table>
    </el-dialog>
  </div>
</template>

<script>
import { getScheduleByCid } from "@/api/system/schedule";
import { listGrades, getGrades, delGrades, addGrades, updateGrades } from "@/api/system/grades";
import { listClasses, getClasses, delClasses, addClasses, updateClasses } from "@/api/system/classes";
import { getToken } from "@/utils/auth";
import { listDiscipline } from "@/api/system/discipline";
import { numberToChinese } from '@/utils/ruoyi.js'
export default {
  dicts: ["sys_week"],
  data() {
    return {
      disciplineList: [],
      kbOpen: false,
      kbTitle: "课表",
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/system/classes/uploadAndUpdateByDivision",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      gradesLoading: false,
      gradesList: [],
      gradeOpen: false,
      // 表单参数
      gradeForm: {
        gid: null,
        gradeName: null
      },
      // 表单校验
      gradeRules: {
        gradeName: [
          { required: true, message: '请输入年级名称', trigger: 'blur' },
        ],
      },
      classesLoading: false,
      classesList: [],
      classOpen: false,
      // 表单参数
      classForm: {
        gid: null,
        className: null
      },
      // 表单校验
      classRules: {
        gid: [
          { required: true, message: '请选择年级', trigger: 'change' },
        ],
        className: [
          { required: true, message: '请输入班级名称', trigger: 'blur' },
        ],
      },
      queryParams: {
        pageNum: 1,
        pageSize: 100,
      },
      currentGid: null,
      kcList: []
    }
  },
  created() {
    this.getGradesList()
    this.getDisciplineList()
  },
  methods: {
    /** 查询学科列表 */
    getDisciplineList() {
      listDiscipline({ pageNum: 1, pageSize: 100 }).then(response => {
        this.disciplineList = response.rows;
      });
    },
    filterLabel(rowIndex, cellIndex) {
      if (cellIndex === 1) {
        return "第" + numberToChinese(rowIndex) + "节课"
      } else {
        const kc = this.kcList.find(a => a.week == cellIndex - 1 && a.sort == rowIndex - 1)
        if (kc) {
          console.log(kc);
          return this.selectDictLabel(this.disciplineList, kc.did, "did", "disciplineName")
        } else {
          return ""
        }
      }
    },
    handleViewClass(row) {
      getScheduleByCid({ cid: row.cid }).then(res => {
        this.kcList = res.data
        this.kbTitle = row.className + "课表"
        this.kbOpen = true
      })
    },
    /** 导入分班学生 */
    handleImport(res, file) {
      if (res.code === 200) {
        this.$message.success("导入成功！")
      } else {
        this.$message.error(res.msg)
      }
    },
    /** 查询年级列表 */
    getGradesList() {
      this.gradesLoading = true;
      this.currentGid = null
      this.classesList = []
      listGrades(this.queryParams).then(response => {
        this.gradesList = response.rows;
        this.gradesLoading = false;
      });
    },
    /** 查询班级列表 */
    getClassesList() {
      this.classesLoading = true;
      listClasses({ ...this.queryParams, gid: this.currentGid }).then(response => {
        this.classesList = response.rows;
        this.classesLoading = false;
      });
    },
    handleExport(row) {
      this.download('system/grades/exportAllStudent', { gid: row.gid }, `${row.gradeName}学生信息.xlsx`)
    },
    /** 选中年级 */
    handleCurrentChange(val) {
      if (val) {
        this.currentGid = val.gid;
        this.getClassesList()
      }
    },
    /** 提交按钮 */
    submitGradeForm() {
      this.$refs["gradeForm"].validate(valid => {
        if (valid) {
          if (this.gradeForm.gid != null) {
            updateGrades(this.gradeForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.gradeOpen = false;
              this.getGradesList();
            });
          } else {
            addGrades(this.gradeForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.gradeOpen = false;
              this.getGradesList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancelGrade() {
      this.gradeOpen = false;
      this.GradeForm = {
        gid: null,
        gradeName: null,
      };
    },
    // 取消按钮
    cancelClass() {
      this.classOpen = false;
      this.classForm = {
        className: null,
      };
    },
    /** 提交按钮 */
    submitClassForm() {
      this.$refs["classForm"].validate(valid => {
        if (valid) {
          if (this.classForm.cid != null) {
            updateClasses(this.classForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.classOpen = false;
              this.getClassesList();
            });
          } else {
            addClasses(this.classForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.classOpen = false;
              this.getClassesList();
            });
          }
        }
      });
    },
    /** 新增按钮操作 */
    handleAddGrades() {
      this.resetGrade()
      this.gradeOpen = true;
    },
    /** 新增按钮操作 */
    handleAddClass(row) {
      this.classForm = {
        gid: row.gid,
        className: null,
      };
      this.classOpen = true;
    },
    resetGrade() {
      this.GradeForm = {
        gid: null,
        gradeName: null,
      };
    },
    resetClass() {
      this.GradeForm = {
        gid: null,
        gradeName: null,
      };
    },
    /** 修改按钮操作 */
    handleUpdateGrade(row) {
      this.resetGrade()
      getGrades(row.gid).then(response => {
        this.gradeForm = response.data;
        this.gradeOpen = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdateClass(row) {
      this.resetClass()
      getClasses(row.cid).then(response => {
        this.classForm = response.data;
        this.classOpen = true;
      });
    },
    /** 删除按钮操作 */
    handleDeleteGrade(row) {
      const gids = row.gid
      this.$modal.confirm('是否确认删除年级编号为"' + gids + '"的数据项？').then(function () {
        return delGrades(gids);
      }).then(() => {
        this.getGradesList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 删除按钮操作 */
    handleDeleteClass(row) {
      const cids = row.cid
      this.$modal.confirm('是否确认删除班级编号为"' + cids + '"的数据项？').then(function () {
        return delClasses(cids);
      }).then(() => {
        this.getClassesList();
        this.$modal.msgSuccess("删除成功");
      })
    },
  }
}
</script>
<style lang="scss" scoped>
table,
tbody {
  width: 100%;
  border-collapse: collapse;
  th,
  td {
    padding: 12px 8px;
    border: 1px solid #ddd;
    text-align: center;
  }
  tr td:nth-child(1),
  th {
    background-color: #f6f6f6;
  }
}
</style>
